using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using VotingSystem.Data;
using VotingSystem.Models;
using System.Security.Claims;

namespace VotingSystem.Controllers
{
    [Authorize]
    public class SurveyResponsesController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly ILogger<SurveyResponsesController> _logger;

        public SurveyResponsesController(ApplicationDbContext context, ILogger<SurveyResponsesController> logger)
        {
            _context = context;
            _logger = logger;
        }

        // GET: SurveyResponses/Create
        public async Task<IActionResult> Create(int surveyId)
        {
            var survey = await _context.Surveys
                .Include(s => s.Questions)
                    .ThenInclude(q => q.Options)
                .FirstOrDefaultAsync(s => s.Id == surveyId);

            if (survey == null)
            {
                return NotFound();
            }

            if (!survey.IsActive)
            {
                TempData["ErrorMessage"] = "该问卷已结束";
                return RedirectToAction("Details", "Surveys", new { id = surveyId });
            }

            if (survey.EndTime.HasValue && survey.EndTime.Value < DateTime.Now)
            {
                TempData["ErrorMessage"] = "该问卷已过期";
                return RedirectToAction("Details", "Surveys", new { id = surveyId });
            }

            ViewBag.Survey = survey;
            return View();
        }

        // POST: SurveyResponses/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(int surveyId, Dictionary<int, string> textResponses, Dictionary<int, int> ratingResponses, Dictionary<int, List<int>> selectedOptions)
        {
            var survey = await _context.Surveys
                .Include(s => s.Questions)
                    .ThenInclude(q => q.Options)
                .FirstOrDefaultAsync(s => s.Id == surveyId);

            if (survey == null || survey.Questions == null)
            {
                return NotFound();
            }

            if (!survey.IsActive)
            {
                TempData["ErrorMessage"] = "该问卷已结束";
                return RedirectToAction("Details", "Surveys", new { id = surveyId });
            }

            if (survey.EndTime.HasValue && survey.EndTime.Value < DateTime.Now)
            {
                TempData["ErrorMessage"] = "该问卷已过期";
                return RedirectToAction("Details", "Surveys", new { id = surveyId });
            }

            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (userId == null)
            {
                return Forbid();
            }

            // 创建问卷回答
            var surveyResponse = new SurveyResponse
            {
                SurveyId = surveyId,
                SubmitTime = DateTime.Now,
                RespondentId = survey.IsAnonymous ? null : userId,
                Survey = survey,
                QuestionResponses = new List<QuestionResponse>()
            };

            _context.Add(surveyResponse);
            await _context.SaveChangesAsync();

            // 处理每个问题的回答
            foreach (var question in survey.Questions)
            {
                if (question.Options == null)
                {
                    continue;
                }

                var questionResponse = new QuestionResponse
                {
                    QuestionId = question.Id,
                    SurveyResponseId = surveyResponse.Id,
                    SurveyResponse = surveyResponse,
                    Question = question,
                    TextResponse = string.Empty,
                    SelectedOptions = new List<OptionResponse>()
                };

                switch (question.Type)
                {
                    case QuestionType.Text:
                        if (textResponses != null && textResponses.TryGetValue(question.Id, out string? textResponse))
                        {
                            questionResponse.TextResponse = textResponse ?? string.Empty;
                        }
                        break;

                    case QuestionType.Rating:
                        if (ratingResponses != null && ratingResponses.TryGetValue(question.Id, out int ratingResponse))
                        {
                            questionResponse.RatingResponse = ratingResponse;
                        }
                        break;

                    case QuestionType.SingleChoice:
                    case QuestionType.MultipleChoice:
                        if (selectedOptions != null && selectedOptions.TryGetValue(question.Id, out List<int>? options) && options != null)
                        {
                            foreach (var optionId in options)
                            {
                                var option = question.Options.FirstOrDefault(o => o.Id == optionId);
                                if (option != null)
                                {
                                    questionResponse.SelectedOptions.Add(new OptionResponse
                                    {
                                        QuestionResponseId = questionResponse.Id,
                                        OptionId = optionId,
                                        QuestionResponse = questionResponse,
                                        Option = option
                                    });
                                }
                            }
                        }
                        break;
                }

                _context.Add(questionResponse);
            }

            await _context.SaveChangesAsync();
            TempData["SuccessMessage"] = "问卷提交成功";
            return RedirectToAction("Details", "Surveys", new { id = surveyId });
        }

        // GET: SurveyResponses/Results/5
        public async Task<IActionResult> Results(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var survey = await _context.Surveys
                .Include(s => s.Questions)
                    .ThenInclude(q => q.Options)
                .Include(s => s.Questions)
                    .ThenInclude(q => q.Responses)
                        .ThenInclude(r => r.SelectedOptions)
                .FirstOrDefaultAsync(s => s.Id == id);

            if (survey == null)
            {
                return NotFound();
            }

            // 检查权限
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (survey.CreatorId != userId)
            {
                return Forbid();
            }

            return View(survey);
        }

        // GET: SurveyResponses/Export/5
        public async Task<IActionResult> Export(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var survey = await _context.Surveys
                .Include(s => s.Questions)
                    .ThenInclude(q => q.Options)
                .Include(s => s.Questions)
                    .ThenInclude(q => q.Responses)
                        .ThenInclude(r => r.SelectedOptions)
                .FirstOrDefaultAsync(s => s.Id == id);

            if (survey == null)
            {
                return NotFound();
            }

            // 检查权限
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (survey.CreatorId != userId)
            {
                return Forbid();
            }

            // 生成CSV文件
            var csv = new System.Text.StringBuilder();
            csv.AppendLine("问题,回答");

            foreach (var question in survey.Questions.OrderBy(q => q.Order))
            {
                foreach (var response in question.Responses)
                {
                    var answer = question.Type switch
                    {
                        QuestionType.Text => response.TextResponse,
                        QuestionType.Rating => response.RatingResponse?.ToString() ?? "",
                        QuestionType.SingleChoice or QuestionType.MultipleChoice =>
                            string.Join(", ", response.SelectedOptions.Select(o => o.Option?.OptionText ?? "")),
                        _ => ""
                    };

                    csv.AppendLine($"\"{question.QuestionText}\",\"{answer}\"");
                }
            }

            var bytes = System.Text.Encoding.UTF8.GetBytes(csv.ToString());
            return File(bytes, "text/csv", $"survey_{survey.Id}_responses.csv");
        }
    }
} 